<template>
	<van-popup :show="showCenter" round>
		<van-form label-width="5em">
			<van-cell-group inset>
				<van-field label="任务总量" v-model="total" required>
					<template #button>
						    <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
						      <van-button type="primary" @click="defaultDistributeTotal" size="mini">自动拆分</van-button>
						      <van-button type="success" @click="distributeTotal" size="mini" style="margin-left: 0.625rem;">手动拆分</van-button>
						    </div>
					</template>
				</van-field>
				<div v-if="tasks.length != 0">
				<van-row style="text-align: center;">
					<van-col span="8">周期</van-col>
					<van-col span="8">任务量</van-col>
					<van-col span="8">%</van-col>
				</van-row>
				<div class="task-list">
					<van-field v-for="(task,index) in tasks" :key="index" v-model="task.quantity" :label="task.point"
						disabled>
						<template #button>
							<van-stepper v-model="task.percentage" :min="0" :max="100" />
						</template>
					</van-field>
				</div>
				</div>
			</van-cell-group>
			<div v-if="tasks.length != 0" style="margin: 16px;">
				<van-button round block type="primary" @click="submit">
					提交
				</van-button>
			</div>
		</van-form>
	</van-popup>
</template>

<script setup lang="ts">
	import { ref, reactive } from 'vue'
	import { showToast } from 'vant';

	const props = defineProps({ showCenter: Boolean, tasktype: String });

	const tasktype = props.tasktype;

	const emits = defineEmits(["update:task"]);

	interface Task {
		point : string;
		quantity : number;
		percentage : number;
	}

	const total = ref(0)

	const startDate = ref('2024-01-01');
	const endDate = ref('2025-01-01');

	const tasks = reactive<Task[]>([]);

	const months = ref([])

	const initRange = () => {
		if ('pop' == tasktype) {
			months.value = getPopMonthRange(startDate.value, endDate.value);
		} else {
			months.value = getExpMonthRange(startDate.value, endDate.value);
		}
		months.value.forEach((month) => {
			tasks.push({
				point: month,
				quantity: 0,
				percentage: 0
			})
		})
	}

	const getPopMonthRange = (startDate : string, endDate : string) => {
		// 创建 Date 对象
		let start = new Date(startDate);
		let end = new Date(endDate);
		// 结果数组
		let months = [];
		// 逐月循环
		while (start <= end) {
			// 格式化年月
			let year = start.getFullYear();
			let month = (start.getMonth() + 1).toString().padStart(2, '0'); // 保证两位数
			months.push(`${year}-${month}`);
			// 增加一个月
			start.setMonth(start.getMonth() + 1);
		}
		return months;
	}

	const getExpMonthRange = (startDate : string, endDate : string) : string[] => {
		const start = new Date(startDate); // 转换起始日期
		const end = new Date(endDate); // 转换结束日期
		const result : string[] = [];

		// 辅助函数：根据月份计算季度
		const getQuarter = (month : number) : number => {
			return Math.floor(month / 3) + 1; // 计算季度：1月-3月 -> 第1季度，4月-6月 -> 第2季度，以此类推
		};

		// 从 startDate 开始，按季度推进
		let currentDate = new Date(start);

		// 循环直到当前日期超过 endDate
		while (currentDate <= end) {
			const year = currentDate.getFullYear(); // 获取当前年份
			const month = currentDate.getMonth(); // 获取当前月份 (0-11)
			const quarter = getQuarter(month); // 计算当前季度

			// 记录季度信息
			result.push(`${year}年${quarter}季度`);

			// 跳到下一个季度
			currentDate.setMonth(currentDate.getMonth() + 3); // 增加3个月进入下一个季度
		}

		return result;
	};

	// 计算每个任务的 quantity 和 percentage
	const defaultDistributeTotal = () => {

		initRange();

		const numTasks = tasks.length;
		// 计算每个任务的基础分配量（向下取整）
		const baseQuantity = Math.floor(total.value / numTasks);
		// 计算所有任务分配后的总数量
		let allocatedQuantity = baseQuantity * numTasks;
		// 计算剩余的部分
		const remainder = total.value - allocatedQuantity;
		// 分配 quantity
		tasks.forEach((task, index) => {
			task.quantity = baseQuantity;
			// 将余数分配到最后一个任务
			if (index == numTasks - 1) {
				task.quantity += remainder;
			}
		});
		// 计算每个任务的百分比（保留整数部分）
		tasks.forEach((task) => {
			task.percentage = Math.floor((task.quantity / total.value) * 100);
		});
		// 确保百分比总和为 100，可能需要将余数调整到最后一个任务
		const totalPercentage = tasks.reduce((sum, task) => sum + task.percentage, 0);
		const percentageRemainder = 100 - totalPercentage;
		// 将百分比余数加到最后一个任务
		tasks[tasks.length - 1].percentage += percentageRemainder;
	};

	// 计算任务数量
	const distributeTotal = () => {
		clearQuantity();
		const nonZeroTasks = tasks.filter(task => task.percentage > 0); // 过滤掉百分比为0的任务
		const nonZeroPercentage = nonZeroTasks.reduce((sum, task) => sum + task.percentage, 0);

		// 1. 确保总的百分比为100%
		if (tasks.reduce((sum, task) => sum + task.percentage, 0) != 100) {
			showToast('百分比总和必须为100%');
			return;
		}

		// 2. 计算任务的数量分配
		let totalAssigned = 0;  // 已分配的数量

		// 归一化剩余百分比（不包含百分比为0的任务）
		nonZeroTasks.forEach(task => {
			const normalizedPercentage = (task.percentage / nonZeroPercentage) * 100;  // 归一化
			const calculatedQuantity = Math.floor((normalizedPercentage / 100) * total.value);
			task.quantity = calculatedQuantity;
			totalAssigned += task.quantity;
		});

		// 3. 处理余数：将剩余的数量分配给最后一个任务
		let remainder = total.value - totalAssigned;
		if (remainder != 0) {
			const lastNonZeroTask = nonZeroTasks[nonZeroTasks.length - 1];
			lastNonZeroTask.quantity += remainder;  // 将余数加到最后一个任务
		}

		// 4. 更新百分比：基于新的数量更新百分比
		tasks.forEach(task => {
			if (task.percentage > 0) {
				task.percentage = Math.round((task.quantity / total.value) * 100);
			}
		});

		// 5. 确保任务总量与百分比匹配
		const totalQuantity = tasks.reduce((sum, task) => sum + task.quantity, 0);
		if (totalQuantity != total.value) {
			console.warn("分配后的任务数量总和与总量不符！");
		}
	};

	const clearQuantity = () => {
		tasks.forEach((task) => {
			task.quantity = 0;
		});
	}

	const submit = () => {
		emits("update:task", tasks)
	}
</script>

<style scoped>
	.task-list {
		max-height: 800px;
		/* 设置任务列表区域的最大高度 */
		overflow-y: auto;
		/* 如果内容超出，显示垂直滚动条 */
	}
</style>